import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { LoginResponse } from '@/types/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('')
  const userInfo = ref<Omit<LoginResponse, 'token' | 'type'> | null>(null)
  const isLoggedIn = ref(false)

  // 设置用户信息和token
  const setUserInfo = (loginResponse: LoginResponse) => {
    const { token: accessToken, type, ...rest } = loginResponse
    // 确保token格式正确
    token.value = accessToken.startsWith('Bearer ') 
      ? accessToken 
      : `Bearer ${accessToken}`
    userInfo.value = rest
    isLoggedIn.value = true
    
    // 保存到localStorage
    localStorage.setItem('token', token.value)
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = null
    isLoggedIn.value = false
    
    // 清除localStorage
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 初始化时从localStorage恢复状态
  const initializeFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (storedToken && storedUserInfo) {
      token.value = storedToken
      userInfo.value = JSON.parse(storedUserInfo)
      isLoggedIn.value = true
      console.log('已从localStorage恢复用户状态:', {
        token: token.value,
        userInfo: userInfo.value
      })
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    setUserInfo,
    logout,
    initializeFromStorage
  }
}) 